package cn.jsp.spring.dao;

import cn.jsp.spring.domain.Stu;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository //自动识别为一个bean
public class StuDao {
  @Autowired //自动绑定，默认按照类型绑定
  DataSource dataSource;
  String sql = "select * from stu";

  @SneakyThrows
  public List<Stu> query(){
    List<Stu> stus=new ArrayList<>();
    try (Connection con = dataSource.getConnection();
         PreparedStatement pstmt = con.prepareStatement(sql);
         ResultSet rs = pstmt.executeQuery()) {
      while (rs.next()) {
        //把ResultSet中的一行转为Stu,ResultSet->Stu
        Stu stu=new Stu();
        stu.setAge(rs.getInt("age"));
        stu.setName(rs.getString("name"));
        stus.add(stu);
      }
    }
    return stus;
  }
}
